﻿using lso_2u_Web应用开发.App_Code.RESTful;
using lso_2u_Web应用开发.App_Code.Service;
using lso_2u_Web应用开发.Models;
using lso_2u_Web应用开发.Models.Database;
using lso_2u_Web应用开发.Models.FormData;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace lso_2u_Web应用开发.Controllers
{
    public class UserApiController : Controller
    {
        private ServiceClient serviceClient;
        private SessionHelper sessionHelper;
        private DressWorkSystemContext _db;

        public UserApiController(DressWorkSystemContext _dressWorkSystemContext, IHttpContextAccessor httpContextAccessor)
        {
            _db = _dressWorkSystemContext;
            sessionHelper = new SessionHelper(httpContextAccessor.HttpContext.Session);
            serviceClient = new ServiceClient(_db);
        }

        public IActionResult Index()
        {
            return View();
        }

        public ActionResult VerifyCode()
        {
            string code = "";
            var bitmap = CreateVerifyCode(out code);
            sessionHelper.CaptchaCode = code;
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Gif);
            return File(stream.ToArray(), "image/gif");
        }

        public static Bitmap CreateVerifyCode(out string code)
        {
            //建立Bitmap对象，绘图
            var bitmap = new Bitmap(200, 60);
            Graphics graph = Graphics.FromImage(bitmap);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
            Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
            Random r = new Random();
            string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";

            StringBuilder sb = new StringBuilder();

            //添加随机的五个字母
            for (int x = 0; x < 5; x++)
            {
                string letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
                sb.Append(letter);
                graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
            }
            code = sb.ToString();

            //混淆背景
            Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
            for (int x = 0; x < 6; x++)
                graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
            return bitmap;
        }

        [HttpGet]
        public IActionResult GetUserInfo()
        {
            var userId = sessionHelper.UserId;
            if (!userId.HasValue)
            {
                return ApiErrorResult.USER_PERMISSION_DENIED;
            }

            var userInfo = serviceClient.getUserService().GetUserInfoById((int)userId);
            return ApiResultHelper.SuccessData(new
            {
                userId = userInfo.Id,
                userName = userInfo.Name,
                userActor = userInfo.Actor
            });
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userInfo">用户信息, 手机号可为空</param>
        /// <returns></returns>
        public IActionResult EditInfo(UserInfo userInfo)
        {
            if (!sessionHelper.IsLogined)
            {
                return ApiErrorResult.USER_PERMISSION_DENIED;
            }

            // 检查手机号是否已占用
            var existUserPhone = _db.Users.Any(x => x.PhoneNumber == userInfo.Phone);
            if (existUserPhone)
            {
                return ApiErrorResult.UPDATE_OBJECT_EXIST;
            }

            // 修改
            var userId = sessionHelper.UserId;
            var user = _db.Users.FirstOrDefault(x => x.Id == userId);
            if (user == null)
            {
                return ApiErrorResult.UPDATE_NOT_CHANGE;
            }
            user.PhoneNumber = userInfo.Phone ?? user.PhoneNumber; ;
            user.Name = userInfo.Name;

            // 检查是否修改成功
            var resultCount = _db.SaveChanges();
            if (resultCount <= 0)
            {
                return ApiErrorResult.UPDATE_NOT_CHANGE;
            }

            return ApiResultHelper.Success();
        }

        public IActionResult EditPassword(string oldPassword, string newPassword)
        {
            if (!sessionHelper.IsLogined)
            {
                return ApiErrorResult.USER_PERMISSION_DENIED;
            }

            // 检查旧密码是否正确
            var checkPassword = _db.Users.Any(x => x.Id == sessionHelper.UserId && x.Password == oldPassword);
            if (!checkPassword)
            {
                return ApiErrorResult.USER_PASSWORD_ERROR;
            }

            // 修改
            var user = _db.Users.FirstOrDefault(x => x.Id == sessionHelper.UserId);
            user.Password = newPassword;

            var resultCount = _db.SaveChanges();
            if (resultCount <= 0)
            {
                return ApiErrorResult.UPDATE_NOT_CHANGE;
            }

            return ApiResultHelper.Success();
        }

        // 发送消息
        [HttpPost]
        public IActionResult SendMessage(ChatMessage chatMessage)
        {
            if (!sessionHelper.IsLogined)
            {
                return ApiErrorResult.USER_PERMISSION_DENIED;
            }

            if(!ModelState.IsValid)
            {
                return ApiErrorResult.UPDATE_INFO_LACK_DATA;
            }

            var message = new Chat();
            message.MessageType = "text";
            message.MessageData = chatMessage.MessageData;
            message.FkSendUserId = sessionHelper.UserId ?? -1;
            message.FkTargetUserId = chatMessage.TargetUserId ?? -1;

            _db.Chats.Add(message);

            var resultCount = _db.SaveChanges();
            if (resultCount <= 0)
            {
                return ApiErrorResult.USER_CHAT_UPDATE_NOTCHANGE;
            }

            return ApiResultHelper.Success();
        }

        // 获取消息
        [HttpGet]
        public IActionResult GetMessage()
        {
            if (!sessionHelper.IsLogined)
            {
                return ApiErrorResult.USER_PERMISSION_DENIED;
            }

            var userId = sessionHelper.UserId;
            var chats = _db.Chats.Where(x => x.FkSendUserId == userId || x.FkTargetUserId == userId).ToList();

            return new OkObjectResult(new
            {
                code = 0,
                msg = "",
                data = new
                {
                    sender = userId,
                    messages = chats
                }
            });
        }

        // 获取消息更新签名, 此值则表示非最新消息
        [HttpGet]
        public IActionResult GetMessageSign()
        {
            if (!sessionHelper.IsLogined)
            {
                return ApiErrorResult.USER_PERMISSION_DENIED;
            }

            var userId = sessionHelper.UserId;
            var chats = _db.Chats.Where(x => x.FkSendUserId == userId || x.FkTargetUserId == userId).Count();

            var msgSign = sessionHelper.UserId.ToString() + chats.ToString();

            return ApiResultHelper.SuccessData(msgSign.ToString());
        }
    }
}
